/**
 * 路由预加载工具
 * 用于在用户登录后预先加载关键页面，提升首次访问速度
 */

// 定义需要预加载的路由模块
const routeModules = {
  dashboard: () => import('@/pages/Dashboard'),
  projects: () => import('@/pages/Projects'),
  conversation: () => import('@/pages/Conversation'),
  hotRadar: () => import('@/pages/HotRadar'),
  editor: () => import('@/pages/Editor'),
}

type RouteKey = keyof typeof routeModules

// 预加载状态缓存
const preloadedRoutes = new Set<RouteKey>()

/**
 * 预加载单个路由
 */
export const preloadRoute = async (routeName: RouteKey): Promise<void> => {
  if (preloadedRoutes.has(routeName)) {
    return // 已经预加载过
  }

  try {
    await routeModules[routeName]()
    preloadedRoutes.add(routeName)
    console.log(`✅ Route preloaded: ${routeName}`)
  } catch (error) {
    console.error(`❌ Failed to preload route: ${routeName}`, error)
  }
}

/**
 * 批量预加载路由
 */
export const preloadRoutes = async (routeNames: RouteKey[]): Promise<void> => {
  const promises = routeNames.map(name => preloadRoute(name))
  await Promise.all(promises)
}

/**
 * 预加载用户登录后常用的页面
 */
export const preloadAuthenticatedRoutes = async (): Promise<void> => {
  // 优先级顺序：Dashboard -> Projects -> Conversation -> HotRadar
  // 使用requestIdleCallback在浏览器空闲时加载，避免阻塞主线程

  if ('requestIdleCallback' in window) {
    requestIdleCallback(() => {
      preloadRoute('dashboard')
        .then(() => preloadRoute('projects'))
        .then(() => preloadRoute('conversation'))
        .then(() => preloadRoute('hotRadar'))
    })
  } else {
    // 降级方案：使用setTimeout
    setTimeout(() => {
      preloadRoute('dashboard')
        .then(() => preloadRoute('projects'))
        .then(() => preloadRoute('conversation'))
        .then(() => preloadRoute('hotRadar'))
    }, 100)
  }
}

/**
 * 清除预加载缓存（仅用于开发调试）
 */
export const clearPreloadCache = (): void => {
  preloadedRoutes.clear()
}
